#include "BubbleGamePlayScence.h"
#include "CRandom.h"
BubbleGamePlayScence::BubbleGamePlayScence()
{
	_match = NULL;
	_bear = NULL;
	_moveAction = NULL;
}

BubbleGamePlayScence::~BubbleGamePlayScence()
{
	SAFE_DEL(_match);
}
CCScene* BubbleGamePlayScence::scene()
{
    CCScene * scene = NULL;
    do 
    {
        // 'scene' is an autorelease object
        scene = CCScene::create();
        CC_BREAK_IF(! scene);

        // 'layer' is an autorelease object
        BubbleGamePlayScence *layer = BubbleGamePlayScence::create();
        CC_BREAK_IF(! layer);

        // add layer as a child to scene
        scene->addChild(layer);
    } while (0);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool BubbleGamePlayScence::init()
{
    bool bRet = false;
    do 
    {
        //////////////////////////////////////////////////////////////////////////
        // super init first
        //////////////////////////////////////////////////////////////////////////

		CC_BREAK_IF(! CCLayerColor::initWithColor(ccc4(0,0,0,255)));

        //////////////////////////////////////////////////////////////////////////
        // add your codes below...
        //////////////////////////////////////////////////////////////////////////

        // 1. Add a menu item with "X" image, which is clicked to quit the program.

        // Create a "close" menu item with close icon, it's an auto release object.
        CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
            "CloseNormal.png",
            "CloseSelected.png",
            this,
            menu_selector(BubbleGamePlayScence::menuCloseCallback));
        CC_BREAK_IF(! pCloseItem);

        // Place the menu item bottom-right conner.
        pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));

        // Create a menu with the "close" menu item, it's an auto release object.
        CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
        pMenu->setPosition(CCPointZero);
        CC_BREAK_IF(! pMenu);

        // Add the menu to HelloWorld layer as a child layer.
        this->addChild(pMenu, 1);

        // 2. Get window size and place the label upper. 
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();

        // 3. Add add a splash screen, show the cocos2d splash image.
		CCSprite* pSprite = CCSprite::spriteWithFile("bg_0.png",CCRect(0,0,480,800));
        CC_BREAK_IF(! pSprite);

        // Place the sprite on the center of the screen
        pSprite->setPosition(ccp(winSize.width/2, winSize.height/2));
		
		
        // Add the sprite to HelloWorld layer as a child layer.
        this->addChild(pSprite, 0);

		//Set up sprite
		// Use batch node. Faster
		CCSpriteBatchNode *parent = CCSpriteBatchNode::create("blocks.png", 100);		
		addChild(parent, 0,kTagParentNode);

		_match = new CMatch();
		_match->addRect(parent,ccp(winSize.width/2, winSize.height/2));
		_match->addRect(parent,ccp(100, 200));
		_match->addRect(parent,ccp(300, 200));
		//nhandt bear
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Bear.plist");
		CCSpriteBatchNode * __pSpriteSheet = CCSpriteBatchNode::batchNodeWithFile("Bear.png");
		this->addChild(__pSpriteSheet, -1);

		CCArray* animFrames = CCArray::createWithCapacity(8);
		char name[50];
		memset(name,NULL,sizeof(name));

		for(int i = 1; i <= 8; ++i) {
			sprintf(name,"bear%d.png",i);
			animFrames->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name));
		}
		CCAnimation *walkAnim = CCAnimation::animationWithSpriteFrames(animFrames,0.1f);
		CCAnimate *animate = CCAnimate::create(walkAnim);

		_bear = CCSprite::createWithSpriteFrameName("bear1.png");
		_bear->setPosition(ccp(winSize.width/2, winSize.height/2));
		addChild(_bear);

		CCActionInterval* seq = (CCActionInterval*)(CCSequence::create( animate,
                       /*CCFlipX::create(true),
                       animate->copy()->autorelease(),
                       CCFlipX::create(false),*/
                       NULL) );
    
		_bear->runAction(CCRepeatForever::create( seq ) );

		//end nhandt

		scheduleUpdate();

		this->setTouchEnabled(true);

        bRet = true;
    } while (0);

    return bRet;
}


void BubbleGamePlayScence::menuCloseCallback(CCObject* pSender)
{
    // "close" menu item clicked
    CCDirector::sharedDirector()->end();
}

void BubbleGamePlayScence::draw()
{
	glDisable(GL_TEXTURE_2D);
	glDisableClientState(GL_COLOR_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
 
	assert(_match);
	_match->draw();
 
	// restore default GL states
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}

void BubbleGamePlayScence::update(float dt)
{	
	_match->update(dt);
}


void BubbleGamePlayScence::registerWithTouchDispatcher()
{
    // higher priority than dragging
    CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, -10, true);
}

bool BubbleGamePlayScence::ccTouchBegan(CCTouch* pTouch, CCEvent* pEvent)
{
    CCPoint touchLocation = pTouch->getLocation();    

    CCPoint nodePosition = convertToNodeSpace( touchLocation );
//    NSLog(@"pos: %f,%f -> %f,%f", touchLocation.x, touchLocation.y, nodePosition.x, nodePosition.y);

	assert(_match);
    _match->MouseDown(b2Vec2(nodePosition.x,nodePosition.y));    
	return true;
}

void BubbleGamePlayScence::ccTouchMoved(CCTouch* pTouch, CCEvent* pEvent)
{
    CCPoint touchLocation = pTouch->getLocation();    
    CCPoint nodePosition = convertToNodeSpace( touchLocation );
    
	assert(_match);
    _match->MouseMove(b2Vec2(nodePosition.x,nodePosition.y));        
}

void BubbleGamePlayScence::ccTouchEnded(CCTouch* pTouch, CCEvent* pEvent)
{
    CCPoint touchLocation = pTouch->getLocation();    
    CCPoint nodePosition = convertToNodeSpace( touchLocation );
    
	assert(_match);
	//CCNode* parent = getChildByTag(kTagParentNode);
	//_match->addRect(parent,nodePosition);

    _match->MouseUp(b2Vec2(nodePosition.x,nodePosition.y));
}